package com.evaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.common.Result;
import com.evaluation.entity.Dept;
import com.evaluation.service.DeptService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门管理控制器
 */
@RestController
@RequestMapping("/api/admin/dept")
public class AdminDeptController {

    @Autowired
    private DeptService deptService;

    /**
     * 分页查询部门列表
     */
    @GetMapping("/list")
    public Result getDeptList(@RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer size,
                              @RequestParam(required = false) String bmmc,
                              @RequestParam(required = false) String bmlx) {
        try {
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();

            if (bmmc != null && !bmmc.trim().isEmpty()) {
                queryWrapper.like("BMMC", bmmc);
            }

            if (bmlx != null && !bmlx.trim().isEmpty()) {
                queryWrapper.eq("BMLX", bmlx);
            }

            // 只查询有效部门
            queryWrapper.eq("BMZT", "0");
            queryWrapper.orderByAsc("BMBH");

            Page<Dept> pageResult = deptService.page(new Page<>(page, size), queryWrapper);

            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询部门列表失败");
        }
    }

    /**
     * 获取所有部门（用于下拉选择）
     */
    @GetMapping("/options")
    public Result getDeptOptions() {
        try {
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BMZT", "0"); // 只查询有效部门
            queryWrapper.orderByAsc("BMBH");
            queryWrapper.select("BMBH", "BMMC", "BMLX");

            List<Dept> deptList = deptService.list(queryWrapper);
            return Result.success(deptList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取部门选项失败");
        }
    }

    /**
     * 根据ID查询部门详情
     */
    @GetMapping("/{bmbh}")
    public Result getDeptById(@PathVariable String bmbh) {
        try {
            Dept dept = deptService.getById(bmbh);
            if (dept == null) {
                return Result.error("部门不存在");
            }
            return Result.success(dept);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询部门详情失败");
        }
    }

    /**
     * 新增部门
     */
    @PostMapping
    public Result addDept(@RequestBody Dept dept) {
        try {
            // 检查部门编号是否已存在
            Dept existingDept = deptService.getById(dept.getBmbh());
            if (existingDept != null) {
                return Result.error("部门编号已存在");
            }

            // 设置默认状态为有效
            dept.setBmzt("0");

            boolean result = deptService.save(dept);
            if (result) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加部门失败");
        }
    }

    /**
     * 更新部门
     */
    @PutMapping("/{bmbh}")
    public Result updateDept(@PathVariable String bmbh, @RequestBody Dept dept) {
        try {
            dept.setBmbh(bmbh);
            boolean result = deptService.updateById(dept);
            if (result) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新部门失败");
        }
    }

    /**
     * 删除部门（逻辑删除）
     */
    @DeleteMapping("/{bmbh}")
    public Result deleteDept(@PathVariable String bmbh) {
        try {
            Dept dept = new Dept();
            dept.setBmbh(bmbh);
            dept.setBmzt("1"); // 设置为无效状态

            boolean result = deptService.updateById(dept);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除部门失败");
        }
    }

    /**
     * 批量导入部门
     */
    @PostMapping("/import")
    public Result importDepts(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 读取Excel文件
            List<Dept> deptList = ExcelUtil.readExcel(file, Dept.class);
            
            if (deptList.isEmpty()) {
                return Result.error("Excel文件中没有有效数据");
            }

            int successCount = 0;
            int errorCount = 0;

            for (Dept dept : deptList) {
                try {
                    // 验证必填字段
                    if (dept.getBmbh() == null || dept.getBmbh().trim().isEmpty() ||
                        dept.getBmmc() == null || dept.getBmmc().trim().isEmpty()) {
                        errorCount++;
                        continue;
                    }

                    // 检查部门编号是否已存在
                    Dept existingDept = deptService.getById(dept.getBmbh());
                    if (existingDept == null) {
                        // 设置默认值
                        if (dept.getBmlx() == null) dept.setBmlx("0");
                        if (dept.getBmzt() == null) dept.setBmzt("0");
                        
                        deptService.save(dept);
                        successCount++;
                    } else {
                        // 更新现有部门
                        if (dept.getBmlx() != null) existingDept.setBmlx(dept.getBmlx());
                        if (dept.getBmmc() != null) existingDept.setBmmc(dept.getBmmc());
                        if (dept.getBmzt() != null) existingDept.setBmzt(dept.getBmzt());
                        
                        deptService.updateById(existingDept);
                        successCount++;
                    }
                } catch (Exception e) {
                    errorCount++;
                    e.printStackTrace();
                }
            }

            return Result.success("导入完成，成功：" + successCount + "条，失败：" + errorCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入部门失败：" + e.getMessage());
        }
    }

    /**
     * 下载部门导入模板
     */
    @GetMapping("/template/download")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 创建模板数据
            List<Map<String, Object>> templateData = new ArrayList<>();
            
            // 添加示例数据
            Map<String, Object> example1 = new HashMap<>();
            example1.put("部门编号", "11001");
            example1.put("部门名称", "示例职能部门");
            example1.put("部门类型", "0");
            example1.put("部门状态", "0");
            templateData.add(example1);
            
            Map<String, Object> example2 = new HashMap<>();
            example2.put("部门编号", "11201");
            example2.put("部门名称", "示例二级学院");
            example2.put("部门类型", "1");
            example2.put("部门状态", "0");
            templateData.add(example2);
            
            Map<String, Object> example3 = new HashMap<>();
            example3.put("部门编号", "11301");
            example3.put("部门名称", "示例社区");
            example3.put("部门类型", "2");
            example3.put("部门状态", "0");
            templateData.add(example3);

            // 导出Excel
            ExcelUtil.exportExcel(response, "部门导入模板", templateData);
            
        } catch (Exception e) {
            e.printStackTrace();
            // 如果导出失败，返回错误信息
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
